package com.xiaowu.springboot.controller;

import com.xiaowu.springboot.constant.MessageConstant;
import com.xiaowu.springboot.domain.LoginUser;
import com.xiaowu.springboot.domain.User;
import com.xiaowu.springboot.dto.UserDTO;
import com.xiaowu.springboot.dto.UserLoginDTO;
import com.xiaowu.springboot.dto.UserRegisterDTO;
import com.xiaowu.springboot.exception.UserNotLoginException;
import com.xiaowu.springboot.result.Result;
import com.xiaowu.springboot.service.UserService;
import com.xiaowu.springboot.utils.JwtUtil;
import com.xiaowu.springboot.vo.UserLoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/user")
@Tag(name = "用户管理", description = "用户相关操作")
public class UserController {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private UserService userService;

    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("测试成功");
    }

    @Operation(summary = "用户登录", description = "向前端返回token")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);

        log.info("开始身份认证...");
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(userLoginDTO.getUsername(), userLoginDTO.getPassword())
        );

        if(Objects.isNull(authentication)) {
            throw  new UserNotLoginException("登录失败");
        }
        log.info("认证结果：{}", authentication);


        // 如果成功，将认证信息存入 SecurityContext
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 获取用户信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        User user = loginUser.getUser(); // 假设 LoginUser 类中有 getUser() 方法


        // 使用 JwtUtil 生成 JWT
        String token = JwtUtil.generateToken(user.getUsername());
        log.info("生成的JWT：{}", token);

        // 返回登录信息
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .avatarUrl(user.getAvatarUrl())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @Operation(summary = "用户注册", description = "向前端返回状态码")
    @PostMapping("/register")
    public Result<Object> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        int insert = userService.insertUser(userRegisterDTO);

        if (insert != 0) {
            return Result.success(MessageConstant.REGISTER_SUCCESS);
        } else {
            return Result.error(MessageConstant.REGISTER_FAIL);
        }
    }

    @Operation(summary = "用户修改信息")
    @PostMapping("/update")
    public Result<Object> updateUser(@RequestBody UserDTO userDTO) {
        int update = userService.updateUser(userDTO);
        if (update == 0) {
            return Result.error(MessageConstant.UPDATE_FAIL);
        }
        return Result.success(MessageConstant.UPDATE_SUCCESS);
    }

    @Operation(summary = "用户信息回显")
    @GetMapping("/one")
    public Result<User> selectUserById(@RequestParam(name = "id") Long id) {
        User user = userService.selectUserById(id);
        return Result.success(user);
    }

    @Operation(summary = "用户退出登录")
    @PostMapping("/logout")
    public Result<String> logout(@RequestHeader("Authorization") String token) {
        log.info("用户退出登录，token：{}", token);
        // 无需具体处理，前端丢弃 token 即可
        return Result.success("退出成功");
    }


}
